package com.psct.ui;

//

/*
 * Copyright (C) 2010 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.psct.Constant;
import com.psct.R;
import com.psct.ThreadPool;
import com.psct.bean.TextData;
import com.psct.bean.TextRes;
import com.psct.data.PSCTDatabase;
import com.psct.web.HttpUtil;

/**
 * 课本列表activity 使用frament展示
 */
@SuppressWarnings("all")
public class BookListActivity extends SherlockFragmentActivity {

	public static int bookId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 先给Activity注册界面进度条功能
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);//
		this.getWindow().setBackgroundDrawableResource(R.drawable.bg);
		ActionBar actionBar = this.getSupportActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.actionbar_bg));
		// setProgressBarIndeterminateVisibility(true);// 在需要显示进度条的时候调用这个方法
		setSupportProgressBarIndeterminateVisibility(false);// 在不需要显示进度条的时候
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		// 获得需要显示第几本课本的课文；
		bookId = this.getIntent().getIntExtra("num", -1) + 1;
		FragmentManager fm = getSupportFragmentManager();
		// 创建一个课文列表的frament并绑定
		if (fm.findFragmentById(android.R.id.content) == null) {
			TextListFragment list = new TextListFragment();
			fm.beginTransaction().add(android.R.id.content, list).commit();
		}
	}

	public void showProgress() {
		setSupportProgressBarIndeterminateVisibility(true);
	}

	public void hideProgress() {
		setSupportProgressBarIndeterminateVisibility(false);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			this.finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 课文列表frament内部类
	 * 
	 * @author zjingchuan
	 * 
	 */
	public static class TextListFragment extends SherlockListFragment {
		MyAdapter mAdapter;
		List<TextData> dataList;
		String mCurFilter;
		Handler handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case Constant.MESSAGE_LOAD_DONE:
					Log.v("booklist", "更新完毕：" + dataList.size());
					mAdapter.notifyDataSetChanged();
					setListShown(true);
					((BookListActivity) getActivity()).hideProgress();
					break;
				case Constant.MESSAGE_NOT_NEW:
					Toast.makeText(getActivity(), "没有新的内容", Toast.LENGTH_SHORT).show();
					break;
				case Constant.MESSAGE_UPDATE_DONE:
					((BookListActivity) getActivity()).hideProgress();
					mAdapter.notifyDataSetChanged();
					break;
				case Constant.MESSAGE_NET_ERR:
					Toast.makeText(getActivity(), "网络或服务器异常，更新失败", Toast.LENGTH_SHORT).show();
					setListShown(true);
					((BookListActivity) getActivity()).hideProgress();
					break;
				}
			}

		};

		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			// 如果没有任何内容，提示
			setEmptyText("抱歉，此课本还没收录任何课文，敬请期待");
			// 是否需要在动作条显示菜单
			setHasOptionsMenu(true);
			getListView().setCacheColorHint(android.R.color.transparent);
			// 创建一个空的adapter
			dataList = new ArrayList<TextData>();
			mAdapter = new MyAdapter(getActivity(), dataList);
			setListAdapter(mAdapter);
			// 开始显示原型进度条
			setListShown(false);
			// 加载数据
			// getLoaderManager().initLoader(0, null, this);
			getData(bookId);
		}

		/**
		 * 开启一个线程 去获取数据
		 * 
		 * @param curIndex
		 *            当前课本的下标
		 */
		private void getData(final int curIndex) {
			ThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					List tempList;
					PSCTDatabase db = new PSCTDatabase(getActivity());
					tempList = db.querryTextByBookId(curIndex);
					// 如果本地没有数据则去服务器查询，并将结果保存在数据库
					if (tempList.isEmpty()) {
						TextRes res = new HttpUtil(getActivity()).getBook("-1",
								String.valueOf(curIndex));
						if (res != null) {
							tempList = res.textList;
						} else {
							handler.sendEmptyMessage(Constant.MESSAGE_NET_ERR);
						}

						if (tempList != null && tempList.size() > 0) {
							db.addData(curIndex, tempList);
							dataList.addAll(tempList);
						}
					} else {
						dataList.addAll(tempList);
					}
					// 主线程上更新UI
					handler.sendEmptyMessage(Constant.MESSAGE_LOAD_DONE);
				}

			});

		}

		/**
		 * 更新数据
		 */
		public void upData() {
			ThreadPool.execute(new Runnable() {

				@Override
				public void run() {
					List tempList = null;
					TextRes res = new HttpUtil(getActivity()).getBook("-1", String.valueOf(bookId));
					if (res != null) {
						tempList = res.textList;
						if (tempList != null) {
							PSCTDatabase db = new PSCTDatabase(getActivity());
							// 更新列表
							dataList.clear();
							dataList.addAll(tempList);
							// 更新数据库
							db.clearTbl(db.TABLE_TEXT);
							db.addData(bookId, dataList);
							handler.sendEmptyMessage(Constant.MESSAGE_UPDATE_DONE);
						}
					} else {
						handler.sendEmptyMessage(Constant.MESSAGE_NET_ERR);
					}
				}

			});

		}

		@Override
		public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
			// SearchView searchView = new
			// SearchView(((SherlockFragmentActivity) getActivity())
			// .getSupportActionBar().getThemedContext());
			// searchView.setQueryHint("输入课文标题");
			// menu.add("搜索")
			// .setIcon(R.drawable.abs__ic_search_api_holo_light)
			// .setActionView(searchView)
			// .setShowAsAction(
			// MenuItem.SHOW_AS_ACTION_IF_ROOM
			// | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
			menu.add(0, Constant.MENU_UPLOAD, 0, "更新数据").setShowAsAction(
					MenuItem.SHOW_AS_ACTION_WITH_TEXT | MenuItem.SHOW_AS_ACTION_IF_ROOM);
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			switch (item.getItemId()) {
			case Constant.MENU_UPLOAD:
				upData();
				((BookListActivity) getActivity()).showProgress();
			}
			return super.onOptionsItemSelected(item);
		}

		@Override
		public void onListItemClick(ListView l, View v, int position, long id) {
			Log.i("FragmentComplexList", "Item clicked: " + id);
			Intent intent = new Intent(this.getActivity(), TextShowActivity.class);
			intent.putExtra("textId", dataList.get(position).getId());
			intent.putExtra("textTitle", dataList.get(position).getTitle());
			this.startActivity(intent);
		}
	}

	public static class MyAdapter extends BaseAdapter {
		private List<TextData> list;
		private LayoutInflater flater;

		public MyAdapter(Context context, List<TextData> list) {
			this.list = list;
			flater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = flater.inflate(R.layout.list_item_text, null);
				holder = new ViewHolder();
				convertView.setTag(holder);
				holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
				holder.tvOther = (TextView) convertView.findViewById(R.id.tv_others);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			TextData text = list.get(position);
			holder.tvTitle.setText(position + 1 + " . " + text.getTitle());
			Log.v("", text.getCriticismCount() + "");
			holder.tvOther.setText("评论" + "(" + text.getCriticismCount() + ")");
			return convertView;
		}

		class ViewHolder {
			TextView tvTitle, tvOther;
		}

	}
}
